<template>
    <div class="apply-client-container">
        <el-card class="apply-form">
            <template #header>
                <div class="card-header">
                    <div class="header-title">
                        <h2>申请第三方系统授权</h2>
                    </div>
                    <div class="header-button">
                        <el-button type="success" link class="my-applications-btn" @click="openMyApplications">我的申请</el-button>
                    </div>
                </div>
            </template>

            <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="apply-form-content">
                <el-form-item label="应用名称" prop="clientName">
                    <el-input v-model="formData.clientName" placeholder="请输入应用名称" />
                </el-form-item>

                <el-form-item label="应用Logo" prop="clientLogo">
                    <div class="logo-container">
                        <el-upload class="logo-uploader" :show-file-list="false" :before-upload="beforeLogoUpload">
                            <img v-if="formData.clientLogo" :src="address.minioUrl + 'image/' + formData.clientLogo"
                                class="logo" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                        <el-button v-if="formData.clientLogo" type="danger" link class="delete-logo-btn"
                            @click="handleDeleteLogo">
                            删除图片
                        </el-button>
                    </div>
                    <div class="upload-tip">建议尺寸：200x200px，支持jpg、png格式</div>
                </el-form-item>

                <el-form-item label="应用域名" prop="clientHostname">
                    <el-input v-model="formData.clientHostname" placeholder="请输入应用域名，例如：example.com" />
                </el-form-item>

                <el-form-item label="授权范围" prop="scopes">
                    <el-checkbox-group v-model="formData.scopes">
                        <el-checkbox label="用户名">用户名</el-checkbox>
                        <el-checkbox label="头像">头像</el-checkbox>
                        <el-checkbox label="邮箱">邮箱</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleSubmit" :disabled="buttonDisable">提交申请</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 我的申请对话框 -->
        <el-dialog
            v-model="myApplicationsVisible"
            title="我的申请记录"
            width="80%"
            destroy-on-close
        >
            <my-applications-view />
        </el-dialog>
    </div>

    <el-dialog v-model="showLoginView" width="800" style="height: 500px;border-radius: 20px;background: linear-gradient(to bottom, #fbf0f2 10%, #ffffff);color: black;" center>
        <template #header>
            <h2 style="margin-top: 0px;">登录</h2>
        </template>
        <LoginView></LoginView> 
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive,onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import request from '@/base/request'
import AppInfo from '@/types/auth/AppInfo'
import { address } from '@/base/address'
import MyApplicationsView from '@/views/auth/myApplicationsView.vue'
import checkLogin from '@/utils/checkLogin'

const showLoginView=ref(false)
const formRef = ref<FormInstance>()
const buttonDisable = ref(false)
const myApplicationsVisible = ref(false)

const formData = ref<AppInfo>({
    clientName: '',
    clientLogo: '',
    clientHostname: '',
    scopes: []
})

const rules = reactive<FormRules>({
    clientName: [
        { required: true, message: '请输入应用名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    clientHostname: [
        { required: true, message: '请输入应用域名', trigger: 'blur' },

    ],
    scopes: [
        { type: 'array', required: true, message: '请至少选择一个授权范围', trigger: 'change' }
    ]
})

// Logo上传前的验证
const beforeLogoUpload = async (file: File) => {

    if (file.size > 10 * 1024 * 1024) {
        ElMessage.error("文件过大，请选择10MB以下的文件");
        return false;
    }

    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!allowedTypes.includes(file.type)) {
        ElMessage.error("文件格式不支持，请上传jpg, png或gif格式的图片");
        return false;
    }
    buttonDisable.value = true;
    try {
        const formData2 = new FormData()
        formData2.append("file", file);

        const response = (await request.post("/video/videoBaseInfo/uploadImage", formData2)).data
        if (response.code == 200) {
            formData.value.clientLogo = response.data;
        } else {
            ElMessage.error(response.msg)
        }
    } catch (error) {
        ElMessage.error('提交失败，请稍后重试')
    } finally {
        buttonDisable.value = false;
        return true
    }


}

// 删除Logo
const handleDeleteLogo = () => {
    formData.value.clientLogo = ''
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return
    
    await formRef.value.validate(async (valid) => {
        if (valid) {
            buttonDisable.value = true
            try {
                const response = await request.post('/user/authClient/applyClient', formData.value)
                if (response.data.code === 200) {
                    ElMessage.success('申请提交成功，请等待审核')
                    resetForm()
                } else {
                    ElMessage.error(response.data.msg)
                }
            }catch (error) {
                ElMessage.error('提交失败，请稍后重试')
            } finally {
                buttonDisable.value = false
            }


        }
    })
}

// 重置表单
const resetForm = () => {
    if (!formRef.value) return
    formRef.value.resetFields()
}

// 打开我的申请对话框
const openMyApplications = () => {
    myApplicationsVisible.value = true
}


onMounted(async () => {
    if(!await checkLogin()){
        ElMessage.error('请先登录')
        showLoginView.value=true
    }
})
</script>

<style scoped>
.apply-client-container {
    padding: 20px;
    max-width: 800px;
    margin: 0 auto;
}

.apply-form {
    margin-top: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    min-height: 40px;
}

.header-title {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    width: 100%;
}

.header-button {
    position: absolute;
    right: 0;
    z-index: 1;
}

.card-header h2 {
    margin: 0;
    font-size: 20px;
    text-align: center;
}

.apply-form-content {
    margin-top: 20px;
}

.logo-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 200px;
    height: 200px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.logo-uploader:hover {
    border-color: #409EFF;
}

.logo-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 200px;
    text-align: center;
    line-height: 200px;
}

.logo {
    width: 200px;
    height: 200px;
    object-fit: cover;
}

.upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.logo-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
}

.delete-logo-btn {
    margin-top: 8px;
}

.my-applications-btn {
    text-decoration: underline;
}
</style>